<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>更换头像</span>
      </div>
    </template>
    <el-row justify="center">
      <el-col :span="24" class="text-center">
        <el-upload
            ref="uploadRef"
            class="avatar-uploader"
            :show-file-list="false"
            :auto-upload="false"
            :action="`/api/user/updateAvatar?userId=${userInfoStore.userInfo.userId}`"
            name="file"
            :headers="{'Authorization': `Bearer ${tokenStore.token}`}"
            :on-success="uploadSuccess"
            :on-change="handleAvatarChange"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar"/>
          <img v-else :src="avatar" class="avatar"/>
        </el-upload>
        <br/>
        <el-button
            type="primary"
            :icon="Plus"
            size="large"
            @click="uploadRef.$el.querySelector('input').click()"
        >
          选择图片
        </el-button>
        <el-button
            type="success"
            :icon="Upload"
            size="large"
            @click="submitUpload"
        >
          上传头像
        </el-button>
      </el-col>
    </el-row>
  </el-card>
</template>

<script setup>
import { Plus, Upload } from '@element-plus/icons-vue'
import { ref } from 'vue'
import avatar from '@/assets/default.png'
import { useTokenStore } from '@/stores/token.js'
import useUserInfoStore from '@/stores/userInfo.js'
import { ElMessage } from 'element-plus'

const uploadRef = ref(null)
const tokenStore = useTokenStore()
const userInfoStore = useUserInfoStore()
const imgUrl = ref(userInfoStore.userInfo.imgUrl ? userInfoStore.userInfo.imgUrl : avatar)

// 上传成功的回调
const uploadSuccess = (response) => {
  console.log('上传成功:', response)
  if (response && response.message) {
    imgUrl.value = response.message // Adjust based on actual response structure
    ElMessage.success('上传成功')
    // 直接更新 Pinia 中的用户信息
    const updatedUserInfo = { ...userInfoStore.userInfo, imgUrl: imgUrl.value }
    userInfoStore.setUserInfo(updatedUserInfo)
  }
}

// 处理图片选择
const handleAvatarChange = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    imgUrl.value = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

// 提交上传
const submitUpload = () => {
  console.log('准备提交上传')
  uploadRef.value.submit()
}
</script>

<style lang="scss" scoped>
.avatar-uploader {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  margin-top: 20px;

  :deep {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
      border-radius: 50%;
      object-fit: cover;
      margin-bottom: 20px;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
      padding: 10px;
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 278px;
      text-align: center;
    }
  }
}

.text-center {
  text-align: center;
}

.page-container {
  padding: 20px;
}

.el-button {
  margin-top: 10px;
  margin-right: 10px;
}
</style>
